﻿using AppMachine.Domain.LogicCom;
using AppMachine.Domain.LogicCom.AppComs;
using Microsoft.EntityFrameworkCore;
using System;
using System.Diagnostics.CodeAnalysis;

namespace AppMachine.EntityFrameworkCore.Repositories.LogicCom;

/// <summary>
/// 应用逻辑组件配置仓储(通过持久化的配置，构建应用逻辑组件)
/// </summary>
public class AppComConfigRepository : IComConfigRepository {
    private readonly AppDbContext _AppComDbContext = new AppDbContextFactory().CreateDbContext(null);
    public void Delete([NotNull] IComConfig comConfig) {
        throw new NotImplementedException();
    }

    public IQueryable<IComConfig> GetAll(string comType=null) {
        if (string.IsNullOrWhiteSpace(comType)) {
            return _AppComDbContext.ComConfigList.Where(it => !string.IsNullOrEmpty(it.ComType));
        }

        return _AppComDbContext.ComConfigList.Where(it => it.ComType.Contains(comType));
    }

    public IComConfig InsertOrUpdate([NotNull] IComConfig comConfig) {

        if (this._AppComDbContext.Entry(comConfig).State == EntityState.Detached) {
            this._AppComDbContext.Add(comConfig);
        }
        

        var xx = _AppComDbContext.SaveChanges();

        return comConfig;
    }

    public IComConfig Query(string comID) {
        return _AppComDbContext.ComConfigList.FirstOrDefault(it => it.ComID == comID)?.SetRepository(this);
    }

    public IComConfig Query(string devID, string unitID, string comType) {
        return _AppComDbContext.ComConfigList
            .FirstOrDefault(it => it.PerpDevID == devID && it.PerpSeatID == unitID && it.ComType.Contains(comType))?.SetRepository(this);
    }

}
